/**
 * @description 获取订单详情
 * @author unhejing (成都-敬宇杰)
 * @date 2020-02-24 下午5:33:14
 */
const {
  validateToken
} = require('../../utils/validateToken.js')
'use strict';
const db = uniCloud.database()
const statusEnum = ['待付款','已取消','到付','已支付','已完成']
async function getOrderDetail(event, context){
	//event为客户端上传的参数
	console.log('event:' + event)
	//event.token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJvcGVuaWQiOiJvdFltSTVQOXFJeXhLbTJ0VTdFWEl3MGhFbEIwIn0.03I1N061TW7o4jI9b3aTpzl4_d8fupn93h2bSkUfXT0"
	let tokenRes = await validateToken(event.token)
	if(tokenRes.code != 0){
		return tokenRes;
	}
	event.user_id = tokenRes.user_id;
	event.user_id = "1";
	// event.id = "253";
	if (event.user_id == '' || !event.user_id) {
		return {
			success: false,
			code: -1,
			msg: '参数错误，缺少用户id'
		}
	}
	if (event.id == '' || !event.id) {
		return {
			success: false,
			code: -1,
			msg: '参数错误，缺少订单id'
		}
	}
	const collection = db.collection('order') // 获取表'order'的集合对象
	let res;
	res = await collection.doc(event.id).get()
	console.log("订单响应数据:" + JSON.stringify(res))
	if (!res.data || res.data.length === 0) {
		return {
			success: false,
			code: -1,
			msg: '暂无数据'
		}
	}
	// 获取订单商品
	console.log("***********************华丽的分割线（获取订单商品）***********************")
	// 获取订单code集合
	let orderCodes = new Array();
	let orderList = res.data;
	orderList.map(o => orderCodes.push(o.order_code))
	console.log("订单编码集合：" + JSON.stringify(orderCodes));
	// 查询订单商品行项目
	const dbCmd = db.command;
	let orderProductList = await db.collection('order_product').where({
		order_code: dbCmd.in(orderCodes)
	}).get();
	console.log("订单商品查询结果：" + JSON.stringify(orderProductList))
	// 组装商品到订单
	let orderProductMap = new Map();
	orderProductList.data.forEach(o => {
		let productList = Array.isArray(orderProductMap.get(o.order_code)) ? orderProductMap.get(o.order_code) : new Array();
		productList.push(o)
		orderProductMap.set(o.order_code, productList)
	})
	// 组装数据
	orderList.map(o => {
		o.statusDesc = statusEnum[o.status];
		o.pay_type = o.pay_type == 0 ? '现金支付' : '微信支付'
		if (Array.isArray(orderProductMap.get(o.order_code))) {
			o.productItemList = orderProductMap.get(o.order_code);
		} else {
			o.productItemList = new Array();
		}
	})
	if (res.id || res.affectedDocs >= 1) {
		return {
			success: true,
			code: 0,
			msg: '成功',
			data: orderList[0]
		}
	}
	return {
		success: false,
		code: -1,
		msg: '服务器内部错误'
	}

};

exports.main = getOrderDetail;


